package com.zuilapsa.jmc.actions;

import com.zuilapsa.jmc.JmcException;
import com.zuilapsa.jmc.model.*;
import com.zuilapsa.jmc.userInterfaces.UserInterfaceSession;

public class ActionSet extends ActionNull {

	public void execute(UserInterfaceSession interfaceSession, String[] args)
			throws JmcException {
		if (args == null || args.length == 0) {
			interfaceSession.printMessageInfo(getHelpString());
		} else {
			String property = args[0];
			String value = null;
			for (int i = 1; i < args.length; i++) {
				if (value == null)
					value = args[i];
				else
					value = value + " " + args[i];
			}
			Level level = interfaceSession.getLevel();

			DefinitionWrapper dw = level.getSubDefinition(property);
			if (dw != null && dw.isProperty()) {
				// TODO shall validate the value (maybe even Property as it
				// knows the definition)
				Property prop;
				if (dw.isGlob()) {
					prop = new Property(dw.definition, property);
				} else {
					prop = new Property(dw.definition);
				}

				if (value == null)
					value = prop.getDefaultValue();
				prop.setValue(value);
				level.addProperty(prop);
				// level.addProperty(property,value);
				interfaceSession.printMessageInfo(property + " = " + value);
			} else if (dw != null && dw.isLevel() && dw.isGlob()) {
				Level subLevel = new Level(level, dw.definition, property);
				level.addLevel(subLevel);
				interfaceSession.printMessageInfo("added: " + property);
			} else {
				interfaceSession.printMessageError("No such property: "
						+ property);
			}
		}
	}

	public String getHelpString() {
		return "Updates property value";
	}
}
